<template>
  <div class="facilities-container">
    <div class="facilities-header">
      <h2>设施查询</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设施名称、位置或类别"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-button
        v-if="userStore.isAdmin()"
        type="primary"
        @click="handleAddClick()"
        class="add-button"
      >
        <el-icon><Plus /></el-icon> 添加设施
      </el-button>
    </div>

    <!-- 设施列表 -->
    <div class="facilities-list">
      <el-empty
        v-if="facilitiesStore.searchedFacilities().length === 0"
        description="暂无设施数据"
      />
      <el-card
        v-for="facility in facilitiesStore.searchedFacilities()"
        :key="facility.id"
        class="facility-card"
        @click="handleCardClick(facility)"
      >
        <div class="facility-info">
          <div class="facility-name">
            <span>{{ facility.name }}</span>
            <el-tag :type="getStatusType(facility.status)" size="small">
              {{ getStatusText(facility.status) }}
            </el-tag>
          </div>
          <div class="facility-location">
            <el-icon><Location /></el-icon>
            <span>{{ facility.location }}</span>
          </div>
          <div class="facility-category">
            <el-icon><Collection /></el-icon>
            <span>{{ facility.category }}</span>
          </div>
          <div class="facility-time">
            <el-icon><Clock /></el-icon>
            <span>{{ facility.openTime }} - {{ facility.closeTime }}</span>
          </div>
        </div>
        <div class="facility-actions" v-if="userStore.isAdmin()">
          <el-button type="primary" size="small" @click.stop="handleEdit(facility)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="danger" size="small" @click.stop="handleDelete(facility)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 设施详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="设施详情" width="90%" destroy-on-close>
      <div v-if="selectedFacility" class="facility-detail">
        <div class="facility-image" v-if="selectedFacility.image">
          <img :src="selectedFacility.image" alt="设施图片" />
        </div>
        <div class="facility-image-placeholder" v-else>
          <el-icon><Picture /></el-icon>
          <span>暂无图片</span>
        </div>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设施名称">{{ selectedFacility.name }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ selectedFacility.location }}</el-descriptions-item>
          <el-descriptions-item label="类别">{{ selectedFacility.category }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            getStatusText(selectedFacility.status)
          }}</el-descriptions-item>
          <el-descriptions-item label="开放时间"
            >{{ selectedFacility.openTime }} -
            {{ selectedFacility.closeTime }}</el-descriptions-item
          >
          <el-descriptions-item label="描述">{{
            selectedFacility.description
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 添加/编辑设施对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="isEditing ? '编辑设施' : '添加设施'"
      width="90%"
      destroy-on-close
    >
      <el-form :model="facilityForm" label-width="80px" ref="formRef" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="facilityForm.name" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="facilityForm.location" placeholder="请输入设施位置" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-input v-model="facilityForm.category" placeholder="请输入设施类别" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="facilityForm.status" placeholder="请选择设施状态" style="width: 100%">
            <el-option label="正常使用" value="active" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="开放时间" prop="openTime">
          <el-time-picker
            v-model="facilityForm.openTime"
            format="HH:mm"
            placeholder="选择开放时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="关闭时间" prop="closeTime">
          <el-time-picker
            v-model="facilityForm.closeTime"
            format="HH:mm"
            placeholder="选择关闭时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="facilityForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入设施描述"
          />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="facility-upload"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-change="handleImageChange"
            :file-list="fileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="showDeleteDialog" title="确认删除" width="300px">
      <div>确定要删除设施 "{{ selectedFacility?.name }}" 吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, type FormInstance, type UploadFile, type UploadUserFile } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Delete,
  Location,
  Collection,
  Clock,
  Picture,
} from '@element-plus/icons-vue'
import { useFacilitiesStore, type Facility } from '../stores/facilities'
import { useUserStore } from '../stores/user'
import { format } from 'date-fns'

const facilitiesStore = useFacilitiesStore()
const userStore = useUserStore()

// 搜索关键词
const searchKeyword = ref('')

// 对话框显示状态
const showDetailDialog = ref(false)
const showEditDialog = ref(false)
const showAddDialog = ref(false)
const showDeleteDialog = ref(false)

// 是否是编辑模式
const isEditing = ref(false)

// 选中的设施
const selectedFacility = ref<Facility | null>(null)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const facilityForm = reactive({
  name: '',
  location: '',
  description: '',
  image: '',
  status: 'active' as 'active' | 'maintenance' | 'closed',
  openTime: null as Date | null, // 修改为 Date 类型
  closeTime: null as Date | null, // 修改为 Date 类型
  category: '',
})

// 文件列表
const fileList = ref<UploadUserFile[]>([])

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设施名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入设施位置', trigger: 'blur' }],
  category: [{ required: true, message: '请输入设施类别', trigger: 'blur' }],
  status: [{ required: true, message: '请选择设施状态', trigger: 'change' }],
  openTime: [{ required: true, message: '请选择开放时间', trigger: 'change' }],
  closeTime: [{ required: true, message: '请选择关闭时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入设施描述', trigger: 'blur' }],
}

// 初始化
onMounted(() => {
  // 设置搜索关键词
  searchKeyword.value = facilitiesStore.searchKeyword
})

// 处理搜索
const handleSearch = () => {
  facilitiesStore.setSearchKeyword(searchKeyword.value)
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'maintenance':
      return 'warning'
    case 'closed':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '正常使用'
    case 'maintenance':
      return '维护中'
    case 'closed':
      return '已关闭'
    default:
      return '未知状态'
  }
}

// 处理卡片点击
const handleCardClick = (facility: Facility) => {
  selectedFacility.value = facility
  showDetailDialog.value = true
}

// 处理编辑
const handleEdit = (facility: Facility) => {
  isEditing.value = true
  selectedFacility.value = facility

  // 将时间字符串转换为 Date 对象
  const parseTimeString = (timeStr: string): Date => {
    const [hours, minutes] = timeStr.split(':').map(Number)
    const date = new Date()
    date.setHours(hours, minutes, 0, 0)
    return date
  }

  // 填充表单数据
  Object.assign(facilityForm, {
    name: facility.name,
    location: facility.location,
    description: facility.description,
    image: facility.image,
    status: facility.status,
    openTime: facility.openTime ? parseTimeString(facility.openTime) : null,
    closeTime: facility.closeTime ? parseTimeString(facility.closeTime) : null,
    category: facility.category,
  })

  // 如果有图片，添加到文件列表
  fileList.value = []
  if (facility.image) {
    fileList.value.push({
      name: 'facility-image.jpg',
      url: facility.image,
    })
  }

  showEditDialog.value = true
}

// 处理删除
const handleDelete = (facility: Facility) => {
  selectedFacility.value = facility
  showDeleteDialog.value = true
}

// 确认删除
const confirmDelete = () => {
  if (selectedFacility.value) {
    const success = facilitiesStore.deleteFacility(selectedFacility.value.id)
    if (success) {
      ElMessage.success('设施删除成功')
      showDeleteDialog.value = false
    } else {
      ElMessage.error('设施删除失败')
    }
  }
}

// 处理添加设施按钮点击
const handleAddClick = () => {
  isEditing.value = false
  selectedFacility.value = null

  // 重置表单数据
  Object.assign(facilityForm, {
    name: '',
    location: '',
    description: '',
    image: '',
    status: 'active',
    openTime: null, // 使用 null 而不是空字符串
    closeTime: null, // 使用 null 而不是空字符串
    category: '',
  })

  fileList.value = []
  showEditDialog.value = true
}

// 处理图片变更
const handleImageChange = (file: UploadFile) => {
  const isImage = file.raw?.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  const isLt2M = file.size! / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 读取图片为base64
  const reader = new FileReader()
  reader.readAsDataURL(file.raw!)
  reader.onload = () => {
    facilityForm.image = reader.result as string
  }

  return true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      ElMessage.error('请填写完整的表单信息')
      return
    }

    // 格式化时间
    const formatTime = (time: string | Date) => {
      if (time instanceof Date) {
        return format(time, 'HH:mm')
      }
      return time
    }

    const facilityData = {
      name: facilityForm.name,
      location: facilityForm.location,
      description: facilityForm.description,
      image: facilityForm.image,
      status: facilityForm.status,
      openTime: facilityForm.openTime ? formatTime(facilityForm.openTime) : '',
      closeTime: facilityForm.closeTime ? formatTime(facilityForm.closeTime) : '',
      category: facilityForm.category,
    }

    let success: boolean | string = false

    if (isEditing.value && selectedFacility.value) {
      // 更新设施
      success = await facilitiesStore.updateFacility(selectedFacility.value.id, facilityData)
      if (success) {
        ElMessage.success('设施更新成功')
        showEditDialog.value = false
      } else {
        ElMessage.error('设施更新失败')
      }
    } else {
      // 添加设施
      success = await facilitiesStore.addFacility(facilityData)
      if (success) {
        ElMessage.success('设施添加成功')
        showEditDialog.value = false
      } else {
        ElMessage.error('设施添加失败')
      }
    }
  } catch (error) {
    console.error('表单提交出错:', error)
    ElMessage.error('操作失败，请重试')
  }
}
</script>

<style lang="scss" scoped>
.facilities-container {
  padding: 20px;

  .facilities-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;

    h2 {
      margin: 0;
      color: #8b5a2b;
    }

    .search-bar {
      flex: 1;
      margin: 0 10px;
      max-width: 500px;
    }

    .add-button {
      white-space: nowrap;
    }
  }

  .facilities-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;

    .facility-card {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      }

      .facility-info {
        margin-bottom: 15px;

        .facility-name {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          font-weight: bold;
          font-size: 16px;
        }

        .facility-location,
        .facility-category,
        .facility-time {
          display: flex;
          align-items: center;
          margin-bottom: 5px;
          color: #666;
          font-size: 14px;

          .el-icon {
            margin-right: 5px;
            font-size: 16px;
          }
        }
      }

      .facility-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
      }
    }
  }

  .facility-detail {
    .facility-image {
      width: 100%;
      height: auto;
      max-height: 400px;
      margin-bottom: 20px;
      border-radius: 8px;
      overflow: hidden;

      img {
        width: 100%;
        height: auto;
        max-height: 400px;
        object-fit: contain;
      }
    }

    .facility-image-placeholder {
      width: 100%;
      height: 200px;
      margin-bottom: 20px;
      border-radius: 8px;
      background-color: #f5f5f5;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #999;

      .el-icon {
        font-size: 40px;
        margin-bottom: 10px;
      }
    }
  }

  .facility-upload {
    width: 100%;
  }
}
</style>
